package com.wangsd.web.coupon.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wangsd.common.basicbean.Result;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.web.MyController;
import com.wangsd.web.coupon.entity.BusinessCoupon;
import com.wangsd.web.coupon.service.BusinessCouponService;
import com.wangsd.web.sys.entity.SysUser;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.util.List;

import static com.wangsd.common.enums.ResultCode.PRARM_NOT_NULL;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author generator
 * @since 2020-01-07
 */
@RestController
@RequestMapping("/coupon/businessCoupon")
public class BusinessCouponController extends MyController {

    @Autowired
    BusinessCouponService businessCouponService;

    @PostMapping("/selectList/{pageNum}/{pageSize}")
    @ApiOperation(value = "查询优惠券列表", notes = "查询优惠券列表", httpMethod = "POST")
    public Result selectList(@PathVariable Integer pageNum,
                             @PathVariable Integer pageSize,
                             @RequestBody @ApiParam(name = "businessCoupon", value = "传入json格式") BusinessCoupon businessCoupon) {
        SysUser loginUser = getUserInfo();

        String code = loginUser.getCode();
        if (businessCoupon.getCode() != null) {
            code = businessCoupon.getCode();
        }

        IPage<BusinessCoupon> resultList = businessCouponService.selectPage(code, pageNum, pageSize, businessCoupon);

        return Result.success(resultList);
    }

    @GetMapping("/delete/{id}")
    @ApiOperation(value = "删除优惠券", notes = "删除优惠券", httpMethod = "GET")
    public Result delete(@PathVariable String id) {
        businessCouponService.removeById(id);
        return Result.success();
    }

    @PostMapping("/add")
    @ApiOperation(value = "添加优惠券", notes = "添加优惠券", httpMethod = "POST")
    public Result add(@RequestBody BusinessCoupon coupon) {

        if (coupon.getCompanyId() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "商圈（公司）" + PRARM_NOT_NULL.getMessage());
        }

        if (coupon.getStockName() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "商家券批次名称" + PRARM_NOT_NULL.getMessage());
        }

        if (coupon.getBelongMerchant() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "批次归属商户号" + PRARM_NOT_NULL.getMessage());
        }

        if (coupon.getGoodsName() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "适用商品范围" + PRARM_NOT_NULL.getMessage());
        }

        if (coupon.getStockType() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "批次类型" + PRARM_NOT_NULL.getMessage());
        }

        if (coupon.getCouponCodeMode() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "券code模式" + PRARM_NOT_NULL.getMessage());
        }

        if (coupon.getId() == null) {
            BusinessCoupon old = businessCouponService.selectRepeat(coupon.getStockName(), coupon.getId());
            if (old != null) {
                return Result.fail("批次号重复！");
            }
        }

        if (coupon.getCouponUseRule() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "核销规则" + PRARM_NOT_NULL.getMessage());
        } else {
            JSONObject couponUseRule = coupon.getCouponUseRule();
            /*券可核销时间*/
            JSONObject couponAvailableTime = couponUseRule.getJSONObject("coupon_available_time");
            String availableBeginTime = couponAvailableTime.getString("available_begin_time");
            if (StringUtils.isBlank(availableBeginTime)) {
                return new Result(PRARM_NOT_NULL.getCode(), "券可核销时间--开始时间" + PRARM_NOT_NULL.getMessage());
            }
            coupon.setAvailableBeginTime(availableBeginTime);

            String availableEndTime = couponAvailableTime.getString("available_end_time");
            if (StringUtils.isBlank(availableEndTime)) {
                return new Result(PRARM_NOT_NULL.getCode(), "券可核销时间--结束时间" + PRARM_NOT_NULL.getMessage());
            }
            coupon.setAvailableEndTime(availableEndTime);

            if ("NORMAL".equals(coupon.getStockType())) {
                /*固定面额满减券使用规则*/
                JSONObject fixedNormalCoupon = couponUseRule.getJSONObject("fixed_normal_coupon");
                Integer discountAmount = fixedNormalCoupon.getInteger("discount_amount");
                if (discountAmount == null) {
                    return new Result(PRARM_NOT_NULL.getCode(), "固定面额满减券使用规则--优惠金额" + PRARM_NOT_NULL.getMessage());
                }
                coupon.setDiscountAmount(discountAmount);
                Integer transactionMinimum = fixedNormalCoupon.getInteger("transaction_minimum");
                if (transactionMinimum == null) {
                    return new Result(PRARM_NOT_NULL.getCode(), "固定面额满减券使用规则--消费门槛" + PRARM_NOT_NULL.getMessage());
                }
                coupon.setTransactionMinimum(transactionMinimum);
            } else if ("DISCOUNT".equals(coupon.getStockType())) {
                /*折扣券使用规则*/
                JSONObject discountCoupon = couponUseRule.getJSONObject("discount_coupon");
                Integer discountPercent = discountCoupon.getInteger("discount_percent");
                if (discountPercent == null) {
                    return new Result(PRARM_NOT_NULL.getCode(), "折扣券使用规则--折扣比例" + PRARM_NOT_NULL.getMessage());
                }
                coupon.setDiscountPercent(discountPercent);

                Integer discountAmountMax = discountCoupon.getInteger("discount_amount_max");
                if (discountAmountMax == null) {
                    return new Result(PRARM_NOT_NULL.getCode(), "折扣券使用规则--折扣比例" + PRARM_NOT_NULL.getMessage());
                }
                coupon.setDiscountPercent(discountPercent);

                Integer transactionMinimum = discountCoupon.getInteger("transaction_minimum");
                if (transactionMinimum == null) {
                    return new Result(PRARM_NOT_NULL.getCode(), "折扣券使用规则--消费门槛" + PRARM_NOT_NULL.getMessage());
                }
                coupon.setTransactionMinimum(transactionMinimum);
            } else if ("EXCHANGE".equals(coupon.getStockType())) {
                /*换购券使用规则*/
                JSONObject exchangeCoupon = couponUseRule.getJSONObject("exchange_coupon");
                Integer exchangePrice = exchangeCoupon.getInteger("exchange_price");
                if (exchangePrice == null) {
                    return new Result(PRARM_NOT_NULL.getCode(), "换购券使用规则--单品换购价" + PRARM_NOT_NULL.getMessage());
                }
                coupon.setExchangePrice(exchangePrice);

                Integer transactionMinimum = exchangeCoupon.getInteger("transaction_minimum");
                if (transactionMinimum == null) {
                    return new Result(PRARM_NOT_NULL.getCode(), "换购券使用规则--消费门槛" + PRARM_NOT_NULL.getMessage());
                }
                coupon.setTransactionMinimum(transactionMinimum);
            }

            String useMethod = couponUseRule.getString("use_method");
            if (StringUtils.isBlank(useMethod)) {
                return new Result(PRARM_NOT_NULL.getCode(), "核销规则--核销方式" + PRARM_NOT_NULL.getMessage());
            }
            coupon.setUseMethod(useMethod);

        }

        if (coupon.getStockSendRule() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "发放规则" + PRARM_NOT_NULL.getMessage());
        } else {
            JSONObject stockSendRule = coupon.getStockSendRule();
            /*发放规则--批次总预算*/
            Integer maxAmount = stockSendRule.getInteger("max_amount");
            if (maxAmount == null) {
                return new Result(PRARM_NOT_NULL.getCode(), "发放规则--批次总预算" + PRARM_NOT_NULL.getMessage());
            }
            coupon.setMaxAmount(maxAmount);

            /*发放规则--批次最大发放个数: 当stock_type为DISCOUNT类型时，必须填写。 */
            if ("DISCOUNT".equals(coupon.getStockType())) {
                Integer maxCoupons = stockSendRule.getInteger("max_coupons");
                if (maxCoupons == null) {
                    return new Result(PRARM_NOT_NULL.getCode(), "发放规则--批次最大发放个数" + PRARM_NOT_NULL.getMessage());
                }
                coupon.setMaxCoupons(maxCoupons);
            }

            /*发放规则--用户最大可领个数*/
            Integer maxCouponsPerUser = stockSendRule.getInteger("max_coupons_per_user");
            if (maxCouponsPerUser == null) {
                return new Result(PRARM_NOT_NULL.getCode(), "发放规则--用户最大可领个数" + PRARM_NOT_NULL.getMessage());
            } else if (maxCouponsPerUser > 100) {
                return new Result(PRARM_NOT_NULL.getCode(), "发放规则--用户可领个数，每个用户最多100张券");
            }
            coupon.setMaxCouponsPerUser(maxCouponsPerUser);
        }

        /*保存*/
        try {
            businessCouponService.add(coupon);
        } catch (BusinessException e) {
            return Result.fail(e.getMsg());
        } catch (IOException e) {
            return Result.fail(e.getMessage());
        }
        return Result.success();
    }

    @ApiOperation(value = "商家券上下架", notes = "商品上下架", httpMethod = "POST")
    @PostMapping("/updateState")
    public Result updateState(@RequestBody BusinessCoupon businessCoupon) {
        if (businessCoupon.getId() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "id" + PRARM_NOT_NULL.getMessage());
        }
        if (businessCoupon.getState() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "state" + PRARM_NOT_NULL.getMessage());
        }
        businessCouponService.updateState(businessCoupon);
        return Result.success();
    }


    @ApiOperation(value = "商家券上下架精品", notes = "商家券上下架精品", httpMethod = "POST")
    @PostMapping("/updateHType")
    public Result updateHType(@RequestBody BusinessCoupon businessCoupon) {
        if (businessCoupon.getId() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "id" + PRARM_NOT_NULL.getMessage());
        }
        if (businessCoupon.getHType() == null) {
            return new Result(PRARM_NOT_NULL.getCode(), "hType" + PRARM_NOT_NULL.getMessage());
        }
        BusinessCoupon newBusiness = new BusinessCoupon();
        newBusiness.setHType(1);
        List<BusinessCoupon> businessCoupons = businessCouponService.selectAll(newBusiness);
        if (businessCoupons != null && businessCoupons.size() >= 3) {
            return new Result(PRARM_NOT_NULL.getCode(), "精品类不能超过三个！");
        }
        businessCouponService.updateState(businessCoupon);
        return Result.success();
    }

    @ApiOperation(value = "pc端核销商家券", notes = "pc端核销商家券", httpMethod = "GET")
    @RequestMapping(value = "/pcPay/{couponCode}", method = RequestMethod.GET)
    @ResponseBody
    public Object pcPay(@PathVariable String couponCode) {
        try {
            SysUser user = getUserInfo();
            if (user == null) {
                return Result.fail("用户未登录");
            }
            if (user.getType() != 4) {
                return Result.fail("没有核销的权限");
            }
            String code = user.getCode();
            businessCouponService.useBusinessCoupon(couponCode, code);
        } catch (BusinessException e) {
            return Result.fail(e.getMsg());
        } catch (IOException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
        return Result.success();
    }

}

